package server;

import game.Player;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.json.JSONObject;
import org.newdawn.slick.BasicGame;

import paintball.PaintballPacketInterpreter;

public class Connection implements Runnable {
	private Player player;
	private BasicGame game;
	private Thread thread;

	public Connection(Player player, BasicGame game) {
		this.player = player;
		this.game = game;
		this.thread = new Thread(this);
		this.thread.start();
	}
	
	@Override
	public void run() {
		Socket socket = this.player.getSocket();
		PaintballPacketInterpreter interpreter = new PaintballPacketInterpreter(this.player);
		BufferedReader inp = null;
		OutputStream os = null;
		
		String line;
		try {
			os = socket.getOutputStream();
			inp = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			// Attempt to receive data
			while((line = inp.readLine()) != null) {
				JSONObject input = new JSONObject(line);
				interpreter.interpret(input);
			}
		} catch (Exception e) {
			try {
				os.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
}
